package com.shopping.service.offline;

import com.shopping.constant.ResponseCode;
import com.shopping.dao.OfflineDao;
import com.shopping.pojo.OfflineMessage;
import com.shopping.pojo.OfflineSys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

@Service
public class OfflineServiceImpl implements OfflineService {

    @Autowired
    OfflineDao offlineDao;

    @Override
    public void addOffline(int senderId, int receiverId, String message) {
        try {
            offlineDao.insertIntoSys(new OfflineSys(senderId, receiverId));
            int sysId = offlineDao.lastInsertId();
            offlineDao.insertIntoMessage(new OfflineMessage(sysId, message));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> selectOffline(int receiverId) {
        Map<String, Object> map = new HashMap<>();
        try{
            List<OfflineSys> offlineSysList = offlineDao.selectFromSys(receiverId);
            if(offlineSysList == null){
                map.put("code", ResponseCode.ENTITY_NOT_EXISTS.getValue());
                return map;
            }
            for(OfflineSys offlineSys: offlineSysList){
                Vector<OfflineMessage> messageVector = offlineDao.selectFromMessage(offlineSys.getId());
                offlineSys.setMessage(messageVector);
            }
            map.put("offlineSysList", offlineSysList);
            map.put("code", ResponseCode.REQUEST_SUCCESSED.getValue());
        }catch (Exception e){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public void deleteOffline(int receiverId) {
        try{
            List<OfflineSys> offlineSysList = offlineDao.selectFromSys(receiverId);
            if(offlineSysList != null){
                for(OfflineSys offlineSys : offlineSysList){
                    offlineDao.deleteFromMessage(offlineSys.getId());
                    offlineDao.deleteFromSys(offlineSys.getSenderId(), offlineSys.getReceiverId());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
